package com.sky.edumanageapi.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.edumanageapi.chapter.pojo.vo.ChapterVO;
import com.sky.edumanageapi.course.mapper.CourseMapper;
import com.sky.edumanageapi.course.pojo.dto.CourseParam;
import com.sky.edumanageapi.course.pojo.dto.CourseQuery;
import com.sky.edumanageapi.course.pojo.entity.Course;
import com.sky.edumanageapi.course.pojo.vo.CourseVO;
import com.sky.edumanageapi.course.service.CourseService;
import com.sky.edumanageapi.order.mapper.OrderMapper;
import com.sky.edumanageapi.order.pojo.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public List<CourseVO> select(CourseQuery courseQuery) {
        log.debug("查询课程列表业务：{}",courseQuery);
        List<CourseVO> courses = courseMapper.selectAll(courseQuery);
        return courses;
    }

    @Override
    public CourseVO selectDetail(Integer courseId) {
        log.debug("查询课程详情业务：{}",courseId);
        CourseVO courseVO = courseMapper.select(courseId);
        return courseVO;
    }

    @Override
    public List<CourseVO> search(CourseParam courseParam) {
        log.debug("搜索课程业务：{}",courseParam);
        List<CourseVO> list = new ArrayList<>();
        if (courseParam != null) {
            list = courseMapper.search(courseParam);
        }
        return list;
    }

    @Override
    public List<CourseVO> myCourse(Integer userId) {
        log.debug("获取用户已支付课程详情，用户ID：{}", userId);

        // 步骤1：获取用户的所有订单
        List<Order> allOrders = orderMapper.selectByUserId(userId);

        // 步骤2：筛选已支付的订单（status = 1）
        List<Order> paidOrders = allOrders.stream()
                .filter(order -> order.getStatus() == 1)
                .collect(Collectors.toList());

        // 步骤3：提取课程ID并去重
        Set<Integer> courseIdSet = paidOrders.stream()
                .map(Order::getCourseId)
                .collect(Collectors.toSet());

        // 步骤4：根据课程ID查询课程详情
        List<CourseVO> courses = new ArrayList<>();
        if (!courseIdSet.isEmpty()) {
            courses = courseMapper.selectByIds(new ArrayList<>(courseIdSet));
        }

        return courses;
    }


}
